package com.sign2024.sign2024project.reporttest;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.List;

public class ExcelExportUtils {
    /**
     * 导出 Excel 文件
     *
     * @param data  导出的数据
     * @param path  导出文件的路径
     * @param clazz 数据类型的类对象
     * @param <T>   数据类型
     * @throws IOException 如果发生 IO 错误
     */
    public static <T> void exportExcel(List<T> data, Path path, Class<T> clazz) throws IOException {
        // 设置导出文件路径
        OutputStream out = new FileOutputStream(path.toFile());

        // 自定义样式，设置字体为宋体
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontName("宋体");
        headWriteFont.setFontHeightInPoints((short) 12);
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontName("宋体");
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        // 执行导出
        EasyExcel.write(out, clazz).sheet("Sheet1").registerWriteHandler(styleStrategy).doWrite(data);

        // 关闭输出流
        out.close();

//        System.out.println("文件导出成功：" + path.toAbsolutePath());
    }

}